<script setup lang="ts">
import { ref } from 'vue'
import 'highlight.js/styles/github-dark.css' // 选择你喜欢的主题
import hljs from 'highlight.js'
import { CopyDocument } from '@element-plus/icons-vue'
import { copyToClipboard } from './utils/tools'
import { ElMessage } from 'element-plus'
const codeBlock = ref<string[]>([])
const texts=ref<string[]>([])
const language = ref('javascript')
const url=ref('')
const onSubmit=() => {
  const param = new FormData()
  param.append('url', url.value)
  //const req=process.env.NODE_ENV === 'production'?'':'/api'
  fetch(import.meta.env.VITE_API_KEY+'/action.php',{
    method: 'POST',
    body: param
  }).then(response => {
    //console.log(response)
    return response.text()
  }).then(todos => {
    console.log(todos)
    //创建docment
    const parser = new DOMParser()
    const doc = parser.parseFromString(todos, 'text/html')
    //console.log(doc)
    //查找code标签
    const codes = doc.getElementsByTagName('code')
    if(codes.length > 0){
      for (let i = 0; i < codes.length; i++) {
        codeBlock.value.push(hljs.highlight(codes[i].innerText, {
          language: language.value
        }).value)
        texts.value.push(codes[i].innerText)
      }
    }
    else{
      ElMessage.error('未找到 <code> tag标签！')
    }
  })
}
const copycode=(text:string)=>{
  copyToClipboard(text)
  ElMessage.success('复制成功！')
}
</script>

<template>
  <div>
    <div class="flex-row gap10">
      网址
          <el-input type="text" v-model="url" class="flex-full" placeholder="请输入网址"/>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </div>
    <!-- <el-input v-model="textarea" autosize type="textarea" placeholder="Please input" /> -->
    <pre v-for="item,i in codeBlock" :key="i" class="code-display flex-col gap10">
      <div class="flex-row gap10 menu"><el-button size="small" :icon="CopyDocument" circle @click="copycode(texts[i])"/></div>
      <code :class="`language-${language}`" v-html="item"></code>
    </pre>
  </div>
</template>

<style scoped lang="less">
.code-display {
  background: #252323;
  border-radius: 8px;
  overflow: auto;
  margin: 16px 0;
  box-shadow: inset 0 0 0 1px #d9dcdf;
}

pre {
  margin: 0;
  padding: 10px;
  overflow-x: auto;
}

code {
  font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
  font-size: 14px;
  line-height: 1.5;
}
</style>
